package com.mid;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lxk on 2019/8/18.
 */
public class Solution106 {

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder == null || postorder == null
                || inorder.length == 0 || postorder.length == 0) {
            return null;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return inPos(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1, map);
    }

    private TreeNode inPos(int[] n, int ni, int nj, int[] s, int si, int sj, Map<Integer, Integer> map) {
        if (si > sj) {
            return null;
        }
        TreeNode head = new TreeNode(s[sj]);
        int index = map.get(s[sj]);
        head.left = inPos(n, ni, index - 1, s, si, si + index - ni - 1, map);
        head.right = inPos(n, index + 1, nj, s, si + index - ni, sj - 1, map);
        return head;
    }

    public static void main(String[] args) {
        int[] arrIn = {9, 3, 15, 20, 7};
        int[] arrPost = {9, 15, 7, 20, 3};
        Solution106 solution106 = new Solution106();
        TreeNode head = solution106.buildTree(arrIn, arrPost);

    }

}
